package com.ithemou.controller;

import com.github.pagehelper.PageInfo;
import com.ithemou.dto.ApkNameDto;
import com.ithemou.dto.AppInfoDto;
import com.ithemou.dto.AppInfoReviewDto;
import com.ithemou.entity.AppInfo;
import com.ithemou.entity.DevUser;
import com.ithemou.service.AppInfoService;
import com.ithemou.utils.SessionUtils;
import com.ithemou.vo.ResultVo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/appInfo")
public class AppInfoController {

    @Autowired
    AppInfoService appInfoService;

    @PostMapping("/page")
    public ResultVo page(@RequestBody AppInfoDto appInfoDto, @RequestParam(defaultValue = "1") Integer pageNo, HttpServletRequest request){
        String token = request.getHeader("token");
        String[] split = token.split("-");
        Long devId = Long.valueOf(split[2]);
        String userType = split[3];
//        if (userType.equals("admin")){
//            appInfoDto.setStatus(1L);
//        }else
        if (userType.equals("dev")){
            appInfoDto.setDevid(devId);
        }

        PageInfo<AppInfo> pageInfo = appInfoService.getPage(appInfoDto,pageNo);
        return ResultVo.success(pageInfo);
    }

    @PostMapping("/saveOrUpdate")
    public ResultVo saveOrUpdate(AppInfo appInfo, MultipartFile file, HttpServletRequest request){
        String token = request.getHeader("token");
        if (file!=null && !file.isEmpty()){
            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            if (file.getSize()>500*1024){
                return ResultVo.error("文件大小大于500k");
            }else if (extension.equalsIgnoreCase("jpg")||
                    extension.equalsIgnoreCase("gif")||
                    extension.equalsIgnoreCase("png")||
                    extension.equalsIgnoreCase("jpeg")){
                String realPath = request.getServletContext().getRealPath("/upload/logo");
                File savePath = new File(realPath);
                if (!savePath.exists()){
                    savePath.mkdirs();
                }

                String fileName = UUID.randomUUID().toString().replace("-", "");
                File saveFile = new File(realPath + File.separator +fileName+"."+extension);

                try {
                    file.transferTo(saveFile);
                    appInfo.setLogopicpath("/upload/logo/"+fileName+"."+extension);
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultVo.error("文件上传失败");
                }

            }else {
                return ResultVo.error("文件格式错误");
            }
        }

        DevUser devUser = (DevUser) SessionUtils.get(token);
        if (appInfo.getId() == null){
            appInfo.setDownloads(0L);
            appInfo.setCreatedby(devUser.getId());
            appInfo.setCreationdate(new Date());
            appInfo.setStatus(1L);
            appInfo.setDevid(devUser.getId());
        }else {
            appInfo.setStatus(1L);
            appInfo.setModifyby(devUser.getId());
            appInfo.setModifydate(new Date());

            AppInfo delApp = appInfoService.getById(appInfo.getId());
            if (delApp.getLogopicpath() != null){
                String realPath = request.getServletContext().getRealPath(delApp.getLogopicpath());
                File delFile = new File(realPath);
                if (delFile.exists()){
                    delFile.delete();
                }
            }
        }

        appInfoService.saveOrUpdate(appInfo);
        return ResultVo.success("新增修改成功");
    }

    @DeleteMapping("/{id}")
    public ResultVo del(@PathVariable Long id,HttpServletRequest request){
        try {
            appInfoService.del(id,request);
            return ResultVo.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("删除删除");
        }
    }

    @GetMapping("/getById/{id}")
    public ResultVo getById(@PathVariable Long id){
        AppInfo appInfo = appInfoService.getById(id);
        return ResultVo.success(appInfo);
    }

    @PostMapping("/varApkName")
    public ResultVo varApkName(@RequestBody ApkNameDto apkNameDto){
        Boolean aBoolean = appInfoService.varApkName(apkNameDto);
        if (aBoolean){
            return ResultVo.success(null);
        }else {
            return ResultVo.error(null);
        }
    }

    @PutMapping("/{id}")
    public ResultVo sale(@PathVariable Long id){
        try {
            appInfoService.sale(id);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("操作失败");
        }
        return ResultVo.success("操作成功");
    }

    @PutMapping("/review")
    public ResultVo review(@RequestBody AppInfoReviewDto appReviewDto){
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(appReviewDto,appInfo);
        appInfoService.saveOrUpdate(appInfo);
        return ResultVo.success("操作成功");
    }

}
